package mbg

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"os"
	"save-kindle/entity"
	"save-kindle/log"
	"save-kindle/source"
	"strings"
	"time"
)

// MBGSource 妙笔阁书源
type MBGSource struct {
	source.BookInfo
}

func NewMbgSource(webSite string) *MBGSource {
	return &MBGSource{
		source.BookInfo{
			WebSite: webSite,
		},
	}
}

func (source *MBGSource) NewBook(bookId, bookName string) {
	source.BookId, source.BookName = bookId, bookName
}

func (source *MBGSource) GetArticle(bookId, bookName string) {
	// 获取目录
	catalog, _ := source.GetCatalog()

	file, err := os.OpenFile(fmt.Sprintf("%s.txt", bookName), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
	if err != nil {
		log.PrintErr(err.Error())
	}
	defer file.Close()

	file.WriteString("\n")

	for i, article := range catalog {
		log.Println(i, article)
		article, _ = source.GetArticleContent(article)

		writeFile(file, article)
	}
}

// GetCatalog 获取文章目录
func (source *MBGSource) GetCatalog() ([]entity.Article, error) {
	// https://www.imiaobige.com/read/46267/
	bookUrl := fmt.Sprintf("https://www.imiaobige.com/read/%s/", source.BookId)

	request, _ := http.NewRequest("GET", bookUrl, nil)

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		log.PrintErr(err.Error())
		return nil, err
	}
	defer response.Body.Close()

	// 解析章节
	document, err := goquery.NewDocumentFromReader(response.Body)
	if err != nil {
		log.PrintErr(err.Error())
		return nil, err
	}

	var articles []entity.Article
	document.Find("#readerlists").Each(func(_ int, idSelection *goquery.Selection) {
		idSelection.Find("ul").Each(func(i int, ulTagSelection *goquery.Selection) {
			// 不是 第0个 最新章节
			if i != 0 {
				ulTagSelection.Find("li").Each(func(_ int, liTagSelection *goquery.Selection) {
					aTag := liTagSelection.Find("a")
					attr, exists := aTag.Attr("href")
					if exists {
						article := entity.Article{
							ArticleUrl:  attr,
							ArticleName: aTag.Text(),
						}
						// log.Println(article)
						articles = append(articles, article)
					}
				})
			}
		})
	})

	return articles, nil
}

// GetArticleContent 获取文章内容
func (source *MBGSource) GetArticleContent(article entity.Article) (entity.Article, error) {
retry:
	request, _ := http.NewRequest("GET", fmt.Sprintf("https://www.imiaobige.com%s", article.ArticleUrl), nil)
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		log.PrintErr(err.Error())
		return article, err
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		time.Sleep(1 * time.Second)
		log.PrintErr("retry", article)
		goto retry
	}

	document, err := goquery.NewDocumentFromReader(response.Body)
	if err != nil {
		log.PrintErr(err.Error())
		return article, err
	}
	document.Find("#content").Each(func(i int, selection *goquery.Selection) {
		html, _ := selection.Html()
		html = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(html, " ", ""), "<br/>", ""), "\n\n", "\n")
		html = strings.ReplaceAll(strings.ReplaceAll(html, "<p>", "\n"), "</p>", "")
		//html = strings.ReplaceAll(strings.ReplaceAll(html, "<p>", "\n"), "</p>", "\n")
		// 去掉末尾的
		// <center>
		//  高速文字手打 <a href="https://www.biquger.com">笔趣阁</a> 捡个杀手做老婆章节列表<a href="/biquge/706/"> https://www.biquger.com/biquge/706/</a></center>
		index := strings.Index(html, "<center")
		if index > -1 {
			article.ArticleContent = html[:index]
		} else {
			article.ArticleContent = html
		}
	})
	if article.ArticleContent == "" {
		// 暂停1s进行重试
		log.PrintErr("retry", article)
		time.Sleep(750 * time.Millisecond)
		goto retry
	}

	time.Sleep(750 * time.Millisecond)
	return article, nil
}

// writeFile 写入文件
func writeFile(file *os.File, v entity.Article) {
	file.WriteString(v.ArticleName)
	file.WriteString(v.ArticleContent + "\n\n")
}
